from django.shortcuts import render, redirect
from django.views import View
from home import models as home_models
from webboard import models
from webboard import forms
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.contrib.auth import get_user_model
from django.utils import timezone


# 以下是讨论区的试图代码
class TypeList(View):
    def get(self, request):
        categories = models.Category.objects.all()
        posts = models.Posts.objects.all().order_by('-publishTime')
        # 获取每篇帖子的标签信息
        for post in posts:
            post.tags_list = post.tags.all()

        return render(request, 'Category.html', {'categories': categories,
                                                 'Posts': posts})


class PostList(View):
    def get(self, request, category_id):
        category = get_object_or_404(models.Category, id=category_id)
        category.clickNumber += 1
        category.save()
        posts = models.Posts.objects.filter(category=category_id).order_by('-publishTime')
        # 获取每篇帖子的标签信息
        for post in posts:
            post.tags_list = post.tags.all()

        return render(request, 'Posts.html', {'Posts': posts, 'categoryId': category_id})


class GetAllPosts(View):
    def post(self, request):
        category_id = request.POST.get('Category_id')
        posts = models.Posts.objects.filter(category=category_id)
        posts_data = []
        for post in posts:
            post_data = {
                'id': post.id,
                'UserId': {
                    'username': post.UserId.username,
                    'avatar_url': str(post.UserId.avatar_url)  # 转换为字符串
                },
                'publishTime': post.publishTime.strftime('%Y-%m-%d %H:%M:%S'),
                'likeNumber': post.likeNumber,
                'browseNumber': post.browseNumber,
                'replyNumber': post.replyNumber,
                'tags_list': [tag.name for tag in post.tags.all()],  # 获取tag名列表
                'title': post.title
            }
            posts_data.append(post_data)

        return JsonResponse({
            'status': True,
            'Posts': posts_data
        })  # , encoder=DjangoJSONEncoder


class PostAddView(View):
    PostForm = forms.AddPostForm()

    # @login_required
    def get(self, request, category_id):
        return render(request, 'AddPost.html', {'PostForm': self.PostForm})

    def post(self, request, category_id):
        if request.user.is_authenticated or request.user.is_superuser:
            # 非超级管理员用户才能执行上传操作
            self.PostForm = forms.AddPostForm(request.POST)
            category = get_object_or_404(models.Category, id=category_id)
            if self.PostForm.is_valid():
                form = self.PostForm.save(commit=False)
                tags = self.PostForm.cleaned_data['tags']
                form.UserId = request.user
                form.category = category
                form.save()
                form.tags.set(tags)

                # 更新相应的 Category 模型实例
                num = len(category.posts_type.all())
                category.containNumber = num
                category.updateTime = timezone.now()
                category.save()

                return redirect('webboardApp:评论区主页')
            else:
                return render(request, 'AddPost.html', {'error_message': '验证失败', 'PostForm': self.PostForm})
        else:
            # 处理表单验证失败的情况
            return render(request, 'AddPost.html',
                          {'error_message': '验证失败', 'PostForm': self.PostForm})


User = get_user_model()


class remarkinfo(View):
    def get(self, request, post_id):
        post = get_object_or_404(models.Posts, id=post_id)  # 获取对应的帖子实例
        post.browseNumber = post.browseNumber + 1
        post.save()
        # datas = models.Posts.objects.filter(id=post_id)
        remarks = models.Remark.objects.filter(postId=post_id).order_by('-publishTime')

        # 获取每个Remark实例关联的Reply实例
        for remark in remarks:
            remark.reply_list = list(remark.replies.all())  # 将 QuerySet 转换为列表
            remark.reply_list.reverse()

        return render(request, "remarkpage.html", {'item': post, 'Remarks': remarks, 'post_id': post_id})


class AddRemarkView(View):
    def post(self, request):
        # 处理评论提交
        frontend_source = request.POST.get('frontend_source')
        content = request.POST.get('content')
        user = get_object_or_404(User, id=request.user.id)

        new_comment_data = {}

        if frontend_source == 'RemarkPage':
            post_id = request.POST.get('post_id')
            post = get_object_or_404(models.Posts, id=post_id)
            # 创建新评论
            NewRemark = models.Remark.objects.create(
                content=content,
                postId=post,
                UserId=user,
            )
            NewRemark.save()
            post.replyNumber += 1
            post.save()

            # 将新评论对象转换成可序列化的字典
            new_comment_data = {
                'id': NewRemark.id,
                'UserId': {
                    'username': NewRemark.UserId.username,
                    'avatar_url': str(NewRemark.UserId.avatar_url),
                },
                'publishTime': NewRemark.publishTime.strftime('%Y-%m-%d %H:%M:%S'),
                'likesNumber': NewRemark.likesNumber,
                'dislikesNumber': NewRemark.dislikesNumber,
                'content': NewRemark.content
            }

        elif frontend_source == 'VideoIntro':
            resource_id = request.POST.get('resource_id')
            resource = get_object_or_404(home_models.Resource, id=resource_id)
            # 创建新评论
            NewRemark = home_models.ResourceRemark.objects.create(
                content=content,
                resource=resource,
                UserId=user,
            )
            NewRemark.save()
            resource.resource_look_count += 1
            resource.save()

            # 将新评论对象转换成可序列化的字典
            new_comment_data = {
                'id': NewRemark.id,
                'UserId': {
                    'username': NewRemark.UserId.username,
                    'avatar_url': str(NewRemark.UserId.avatar_url),
                },
                'publishTime': NewRemark.publishTime.strftime('%Y-%m-%d %H:%M:%S'),
                'likesNumber': NewRemark.likesNumber,
                'dislikesNumber': NewRemark.dislikesNumber,
                'content': NewRemark.content
            }

        # 返回 JSON 响应
        return JsonResponse({
            'status': True,
            'new_comment': new_comment_data
        })  # , encoder=DjangoJSONEncoder


def get_comments(request):
    if request.method == 'POST':
        frontend_source = request.POST.get('frontend_source')

        new_comments = None
        if frontend_source == 'RemarkPage':
            post_id = request.POST.get('post_id')
            # 获取最新的评论
            new_comments = models.Remark.objects.filter(postId=post_id).order_by('publishTime')
        elif frontend_source == 'VideoIntro':
            resource_id = request.POST.get('resource_id')
            new_comments = home_models.ResourceRemark.objects.filter(resource=resource_id).order_by('publishTime')

        # 将评论对象转换成可序列化的字典
        comments_data = []
        for comment in new_comments:
            reply_list = []
            for reply in comment.replies.all().reverse():
                reply_data = {
                    'id': reply.id,
                    'content': reply.content,
                    'author': {
                        'username': reply.author.username,
                        'avatar_url': str(reply.author.avatar_url),
                    },
                    'UserId': {
                        'username': reply.UserId.username,
                        'avatar_url': str(reply.UserId.avatar_url),
                    },
                    'publishTime': reply.publishTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'likes_number': reply.likes_number,
                    'dislikes_number': reply.dislikes_number,
                }
                reply_list.append(reply_data)

            comment_data = {
                'id': comment.id,
                'UserId': {
                    'username': comment.UserId.username,
                    'avatar_url': str(comment.UserId.avatar_url),
                },
                'publishTime': comment.publishTime.strftime('%Y-%m-%d %H:%M:%S'),
                'likesNumber': comment.likesNumber,
                'dislikesNumber': comment.dislikesNumber,
                'reply_list': reply_list,
                'content': comment.content
            }
            comments_data.append(comment_data)

        # 返回 JSON 响应
        return JsonResponse({
            'status': True,
            'comments': comments_data
        })  # , encoder=DjangoJSONEncoder


class PostLikeNumber(View):
    def post(self, request):
        post_id = request.POST.get('post_id')
        post = models.Posts.objects.get(id=post_id)
        #   print(post.likeNumber)
        post.likeNumber += 1
        #   print(post.likeNumber)
        post.save()
        return JsonResponse({'status': True, 'new_like_count': post.likeNumber})


class PostUnlikeNumber(View):
    def post(self, request):
        post_id = request.POST.get('post_id')
        post = models.Posts.objects.get(id=post_id)
        #  print(post.likeNumber)
        if post.likeNumber > 0:
            post.likeNumber -= 1
        post.save()
        # print(post.likeNumber)
        return JsonResponse({'status': True, 'new_like_count': post.likeNumber})


class RemarkClickLike(View):
    def post(self, request):
        frontend_source = request.POST.get('frontend_source')
        remark_id = request.POST.get('remark_id')
        remark = None
        if frontend_source == 'RemarkPage':
            remark = models.Remark.objects.get(id=remark_id)
        elif frontend_source == 'VideoIntro':
            remark = home_models.ResourceRemark.objects.get(id=remark_id)
        #  print(remark.likesNumber)
        remark.likesNumber += 1
        #  print(remark.likesNumber)
        remark.save()
        return JsonResponse({'status': True, 'new_like_count': remark.likesNumber})


class RemarkClickunLike(View):
    def post(self, request):
        frontend_source = request.POST.get('frontend_source')
        remark_id = request.POST.get('remark_id')

        remark = None
        if frontend_source == 'RemarkPage':
            remark = models.Remark.objects.get(id=remark_id)
        elif frontend_source == 'VideoIntro':
            remark = home_models.ResourceRemark.objects.get(id=remark_id)
        #  print(remark.dislikesNumber)
        remark.dislikesNumber += 1
        #  print(remark.dislikesNumber)
        remark.save()
        return JsonResponse({'status': True, 'new_unlike_count': remark.dislikesNumber})


class RemarkClickReply(View):
    def post(self, request):
        frontend_source = request.POST.get('frontend_source')
        remark_id = request.POST.get('remark_id')
        content = request.POST.get('content')
        post_id = request.POST.get('post_id')
        resource_id = request.POST.get('resource_id')
        user = get_object_or_404(User, id=request.user.id)
        NewReply = None
        if frontend_source == 'RemarkPage':
            remark = get_object_or_404(models.Remark, id=remark_id)
            post = get_object_or_404(models.Posts, id=post_id)
            target = remark.UserId  # 该回复的回复对象

            NewReply = models.Reply.objects.create(
                remarkId=remark,
                content=content,
                author=user,
                UserId=target,
                postId=post,
            )
            NewReply.save()

            # print(post.replyNumber)
            num_re = len(post.remark.all())
            num_reply = len(post.reply_to_post.all())
            post.replyNumber = num_re + num_reply
            post.save()
            # print(post.replyNumber)

        elif frontend_source == 'VideoIntro':
            remark = get_object_or_404(home_models.ResourceRemark, id=remark_id)
            resource = get_object_or_404(home_models.Resource, id=resource_id)
            target = remark.UserId  # 该回复的回复对象

            NewReply = home_models.ResourceReply.objects.create(
                remarkId=remark,
                content=content,
                author=user,
                UserId=target,
                resource=resource,
            )
            NewReply.save()

            # print(resource.resource_comments)
            num_re = len(resource.remark_resources.all())
            num_reply = len(resource.reply_to_resource.all())
            resource.resource_comments = num_re + num_reply
            resource.save()
            # print(resource.resource_comments)

        new_comment_data = {
            'id': NewReply.id,
            'UserId': {
                'id': NewReply.UserId.id,
                'username': NewReply.UserId.username,
                'avatar_url': str(NewReply.UserId.avatar_url),
            },
            'author': {
                'id': NewReply.author.id,
                'username': NewReply.author.username,
                'avatar_url': str(NewReply.author.avatar_url),
            },
            'publishTime': NewReply.publishTime.strftime('%Y-%m-%d %H:%M:%S'),
            'likesNumber': NewReply.likes_number,
            'dislikesNumber': NewReply.dislikes_number,
            'content': NewReply.content
        }

        # 返回 JSON 响应
        return JsonResponse({
            'status': True,
            'new_comment': new_comment_data
        })  # , encoder=DjangoJSONEncoder


class ReplyClickReply(View):
    def post(self, request):
        frontend_source = request.POST.get('frontend_source')
        remark_id = request.POST.get('remark_id')
        content = request.POST.get('content')
        reply_id = request.POST.get('reply_id')
        user = get_object_or_404(User, id=request.user.id)

        NewReply = None
        if frontend_source == 'RemarkPage':
            post_id = request.POST.get('post_id')
            remark = get_object_or_404(models.Remark, id=remark_id)
            reply = get_object_or_404(models.Reply, id=reply_id)
            post = get_object_or_404(models.Posts, id=post_id)
            target = reply.UserId  # 该回复的回复对象

            NewReply = models.Reply.objects.create(
                remarkId=remark,
                content=content,
                author=user,
                UserId=target,
                postId=post,
            )
            NewReply.save()
            # print(post.replyNumber)
            num_re = len(post.remark.all())
            num_reply = len(post.reply_to_post.all())
            post.replyNumber = num_re + num_reply
            post.save()

        elif frontend_source == 'VideoIntro':
            resource_id = request.POST.get('resource_id')
            remark = get_object_or_404(home_models.ResourceRemark, id=remark_id)
            reply = get_object_or_404(home_models.ResourceReply, id=reply_id)
            resource = get_object_or_404(home_models.Resource, id=resource_id)
            target = reply.UserId  # 该回复的回复对象

            NewReply = home_models.ResourceReply.objects.create(
                remarkId=remark,
                content=content,
                author=user,
                UserId=target,
                resource=resource,
            )
            NewReply.save()

            # print(resource.resource_comments)
            num_re = len(resource.remark_resources.all())
            num_reply = len(resource.reply_to_resource.all())
            resource.resource_comments = num_re + num_reply
            resource.save()
            # print(resource.resource_comments)

        new_comment_data = {
            'id': NewReply.id,
            'UserId': {
                'id': NewReply.UserId.id,
                'username': NewReply.UserId.username,
                'avatar_url': str(NewReply.UserId.avatar_url),
            },
            'author': {
                'id': NewReply.author.id,
                'username': NewReply.author.username,
                'avatar_url': str(NewReply.author.avatar_url),
            },
            'publishTime': NewReply.publishTime.strftime('%Y-%m-%d %H:%M:%S'),
            'likesNumber': NewReply.likes_number,
            'dislikesNumber': NewReply.dislikes_number,
            'content': NewReply.content
        }

        # print(new_comment_data)

        # 返回 JSON 响应
        return JsonResponse({
            'status': True,
            'new_comment': new_comment_data
        })  # , encoder=DjangoJSONEncoder


class ReplyClickLike(View):
    def post(self, request):
        frontend_source = request.POST.get('frontend_source')
        reply_id = request.POST.get('reply_id')
        reply = None
        if frontend_source == 'RemarkPage':
            reply = models.Reply.objects.get(id=reply_id)

        elif frontend_source == 'VideoIntro':
            reply = home_models.ResourceReply.objects.get(id=reply_id)
        #  print(reply.likes_number)
        reply.likes_number += 1
        #  print(reply.likes_number)
        reply.save()
        return JsonResponse({'status': True, 'new_like_count': reply.likes_number})


class ReplyClickunLike(View):
    def post(self, request):
        frontend_source = request.POST.get('frontend_source')
        reply_id = request.POST.get('reply_id')
        reply = None
        if frontend_source == 'RemarkPage':
            reply = models.Reply.objects.get(id=reply_id)

        elif frontend_source == 'VideoIntro':
            reply = home_models.ResourceReply.objects.get(id=reply_id)

        #  print(reply.dislikes_number)
        reply.dislikes_number += 1
        #  print(reply.dislikes_number)
        reply.save()
        return JsonResponse({'status': True, 'new_unlike_count': reply.dislikes_number})
